#include <stdint.h>
#include <zlog.h>
#include <vector>
#include "treaty_base.h"
#include "dev_data.h"
#include <thread>
#include <memory>
#include <atomic>
#include "serial_app.h"

#define MODBUS_RTU_TTY_NAME "/dev/tnt0"

using namespace std;
class modbus_rtu : public treaty_base
{
private:
    zlog_category_t *modbus_rtu_category = nullptr;
    uint8_t modbus_rtu_slave_addr = 1;
    std::shared_ptr<std::thread> modbus_rtu_thread = nullptr;
    std::atomic<bool> modbus_rtu_thread_exit;

    std::shared_ptr<serial_app> modbus_rtu_serial_app = nullptr;

    vector<uint8_t> packet;

private:
    // 计算 Modbus RTU CRC16
    uint16_t modbus_crc16(uint8_t *buffer, int length);
    uint32_t create_modbus_rtu_packet_rsp_status(vector<uint8_t> &data);
    uint32_t create_modbus_rtu_packet_rsp_data(vector<uint8_t> &data, const PUSH_DATA_TYPE type);
    uint32_t create_modbus_rtu_packet_rsp_others(vector<uint8_t> &data);

    void modbus_rtu_thread_func(void);

public:
    modbus_rtu();
    ~modbus_rtu();
    void set_stop_rtu_thread();
    void wait_rtu_thread_stop();
};
